from aiogram import Bot
from fluentogram import TranslatorRunner

from src.bot.services.locale import Localizator
from src.bot.services.tg_helpers import send_tg_message
from src.bot.worker.exception_handler import exception_handler
from src.core.models.enums import SubscriptionStatus
from src.database.services import SubscriptionService, UserService


@exception_handler
async def notify_expired_subscription(
    ctx,
) -> None:
    """Отправляем сообщение о просроченной подписке"""

    bot: Bot = ctx["bot"]
    localizator: Localizator = ctx["localizator"]
    user_service: UserService = ctx["user_service"]
    subscription_service: SubscriptionService = ctx["subscription_service"]

    expired_subscriptions = await subscription_service.get_expired_subscriptions()
    for subscription in expired_subscriptions:
        user = await user_service.get_user_by_id(subscription.user_id)
        locale: TranslatorRunner = localizator.get_by_locale(user.lang_code)
        await subscription_service.update_subscription_status(
            subscription.id, SubscriptionStatus.expired
        )

        await send_tg_message(
            bot,
            user.telegram_id,
            locale.get("subscription-expired-msg"),
        )
